import java.awt.*;
import javax.swing.JPanel;

import java.awt.geom.Ellipse2D;

@SuppressWarnings("serial")
public class SwingPanel extends JPanel {

	float x = 50.0f, y = 50.0f;
	float velx = 0.002f, vely = 0.002f;
	
	float bx = 10.0f, by = 10.0f;
	float velbx = 0.001f, velby = 0.001f;
	
	/*
	 * Logic
	 */
	public void logic() {
		// Border moving from x = 0 to 300 and y = 0 to 200 and bouncing back
		if(bx < 0 || bx > 300) {
			velbx = -velbx;
		}
		if(by < 0 || by > 200) {
			velby = -velby;
		}
		
		// Ball bouncing off borders
		if(x < bx || x > 700-bx) {
			velx = -velx;
			x += velx;
		}
		if(y < by || y > 500-by) {
			vely = -vely;
			y += vely;
		}
		
		// Move!
		bx += velbx;
		by += velby;
		x += velx;
		y += vely;
	}
	
	/*
	 * Paint loop
	 */
	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D)g;
		
		// Draw stuff
		g2d.draw(new Ellipse2D.Double(x, y, 100, 100));
		
		g2d.drawLine((int)bx, (int)by, (int)bx, 600-(int)by);
		g2d.drawLine(800-(int)bx, (int)by, 800-(int)bx, 600-(int)by);
		
		g2d.drawLine((int)bx, (int)by, 800-(int)bx, (int)by);
		g2d.drawLine((int)bx, 600-(int)by, 800-(int)bx, 600-(int)by);
		
		Toolkit.getDefaultToolkit().sync();
        g.dispose();
	}
	
	/*
	 * Main loop
	 */
	public void run() {
		long time, timedelta, wait;
		
		time = System.currentTimeMillis();
		
		while(true) {
			logic();
			repaint();
			
			timedelta = System.currentTimeMillis() - time;
			wait = 50 - timedelta;
				
			if(wait < 0)
				wait = 2;
				
			try {
				wait(wait);
			} catch(Exception e) { }
			
			time = System.currentTimeMillis();
		}
	}
	
	/*
	 * Initialization
	 */
	public SwingPanel() {
		setBackground(Color.WHITE);
		setDoubleBuffered(true);
	}

}
